package com.example.logicalthinking.broadcastbestpracice;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.os.EnvironmentCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.VideoView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class CameraAlbumActivity extends AppCompatActivity implements View.OnClickListener{

    public static final int TAKE_PHOTO = 1;
    public static final int CHOOSE_PHOTO = 2;
    public static final int PLAY_MEIDA = 3;
    public static final int PLAY_VIDEO = 4;

    private Uri imageUri;
    private ImageView picture;
    private  ImageView choosePicture;
    private MediaPlayer mediaPlayer = new MediaPlayer();
    private VideoView videoView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_album);

        picture = (ImageView) findViewById(R.id.picture);
        Button takePhoto = (Button) findViewById(R.id.take_photo);
        takePhoto.setOnClickListener(this);

        choosePicture = (ImageView) findViewById(R.id.alumphoto);
        Button choose  = (Button) findViewById(R.id.choose_photo);
        choose.setOnClickListener(this);

        // 音乐
        Button play = (Button) findViewById(R.id.play);
        Button pause = (Button) findViewById(R.id.pause);
        Button stop = (Button) findViewById(R.id.stop);
        play.setOnClickListener(this);
        pause.setOnClickListener(this);
        stop.setOnClickListener(this);

        // 视频
        videoView = (VideoView) findViewById(R.id.video_view);
        Button playvideo = (Button) findViewById(R.id.play_video);
        Button pausevideo = (Button) findViewById(R.id.pause_video);
        Button stopvideo = (Button) findViewById(R.id.stop_video);
        playvideo.setOnClickListener(this);
        pausevideo.setOnClickListener(this);
        stopvideo.setOnClickListener(this);
        // 检查权限
        if (ContextCompat.checkSelfPermission(CameraAlbumActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(CameraAlbumActivity.this,
                    new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PLAY_MEIDA);
        }else {
            initMediaPlay();
        }
        // 检查权限
        if (ContextCompat.checkSelfPermission(CameraAlbumActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(CameraAlbumActivity.this,
                    new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PLAY_VIDEO);
        }else {
            initVideoPlay();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.take_photo:{
                // 创建File对象，用于存储拍照后的图片
                // 获取手机sd卡的应用关联缓存目录  照片的名字
                File imageFile = new File(getExternalCacheDir(), "output_image.jpg");
                try {
                    if (imageFile.exists()){
                        imageFile.delete();
                    }
                    imageFile.createNewFile();
                }catch (IOException e){
                    e.printStackTrace();
                }
                // 系统版本为Android 7.0以上
                if (Build.VERSION.SDK_INT >= 24){
                    // 7.0以后直接使用本地真实路径的Uri被认为是不安全的
                    imageUri = FileProvider.getUriForFile(CameraAlbumActivity.this,
                            "com.example.logicalthinking.broadcastbestpracice.fileprovider", imageFile);
                }else {
                    // 将文件对象转换为Uri对象  该对象标识着out_image.jpg这张图片的本地真实路径
                    imageUri = Uri.fromFile(imageFile);
                }
                // 启动相机程序
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); // image capture
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(intent, TAKE_PHOTO);
            }
                break;
            case R.id.choose_photo:{
                // 检查权限
                if (ContextCompat.checkSelfPermission(CameraAlbumActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(CameraAlbumActivity.this,
                            new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, CHOOSE_PHOTO);
                }else {
                    openAlbum();
                }
            }
                break;
            case R.id.play:{
                if (!mediaPlayer.isPlaying()){
                    mediaPlayer.start();
                }
            }
                break;
            case R.id.pause:{
                if (mediaPlayer.isPlaying()){
                    mediaPlayer.pause();
                }
            }
                break;
            case R.id.stop:{
                if (mediaPlayer.isPlaying()){
                    mediaPlayer.reset();
                    initMediaPlay();
                }
            }
                break;
            case R.id.play_video:{
                if (!videoView.isPlaying()){
                    videoView.start();
                }
                Toast.makeText(this, "播放视频", Toast.LENGTH_LONG).show();
            }
            break;
            case R.id.pause_video:{
                if (videoView.isPlaying()){
                    videoView.pause();
                }
            }
            break;
            case R.id.stop_video:{
                if (videoView.isPlaying()){
                    videoView.resume();
                }
            }
            break;
            default:
                break;
        }
    }

    private void openAlbum(){
        // 打开相册
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO);
    }

    private void initMediaPlay(){
       try {
// <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
                // 访问SD卡的权限
            File file = new File(Environment.getExternalStorageDirectory(), "music.mp3");
            mediaPlayer.setDataSource(file.getPath());
            mediaPlayer.prepare();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    private void initVideoPlay(){
        try {
            File file = new File(Environment.getExternalStorageDirectory(), "movie.mp4");
            videoView.setVideoPath(file.getPath());

        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK){
                    try {
                        //将拍摄的照片显示出来  Bitmap图片像素 BitmapFactory是用来加载图片的
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        picture.setImageBitmap(bitmap);
                    }catch (FileNotFoundException e){
                        e.printStackTrace();
                    }
                }
                break;
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK){
                    if (Build.VERSION.SDK_INT >= 19){
                        // 4.4以上系统使用这个方法处理图片
                        handleImageOnKitKat(data);
                    }else {
                        handleImageBeforeKitKat(data);
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case CHOOSE_PHOTO:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    openAlbum();
                }else {
                    Toast.makeText(this, "denied the permission", Toast.LENGTH_LONG).show();
                }
                break;
            case PLAY_MEIDA:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    initMediaPlay();
                }else {
                    Toast.makeText(this, "拒绝权限将无法使用程序", Toast.LENGTH_LONG).show();
                    finish();
                }
                break;
            case PLAY_VIDEO:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    initVideoPlay();
                }else {
                    Toast.makeText(this, "拒绝权限将无法使用程序", Toast.LENGTH_LONG).show();
                    finish();
                }
                break;
        }
    }
    @TargetApi(19)
    private  void handleImageOnKitKat(Intent data){

        String imagePath = null; //图片路径
        Uri u = data.getData(); //content://media/external/images/media/369
        if (DocumentsContract.isDocumentUri(this, u)){
            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(u);
            if ("com.android.providers.media.documents".equals(u.getAuthority())){
                String id = docId.split(":")[1]; //解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);

            }else if ("com.android.providers.downloads.documents".equals(u.getAuthority())){
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("conten://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        }else if ("content".equalsIgnoreCase(u.getScheme())){
            // 如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(u, null);
        }else if ("flie".equalsIgnoreCase(u.getScheme())){
            imagePath = u.getPath();
        }
        displayImage(imagePath);
    }

    private void handleImageBeforeKitKat(Intent data){
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    private String getImagePath(Uri uri, String selection){
        String path = null;
        // 通过Uri和seleciton来获取真实的图片路径
        Cursor cur = getContentResolver().query(uri, null, selection, null, null);
        if (cur != null){
            if (cur.moveToFirst()){
                path = cur.getString(cur.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cur.close();
        }
        return path;
    }

    private void  displayImage(String imagePath){
        if (imagePath != null){
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            choosePicture.setImageBitmap(bitmap);
        }else {
            Toast.makeText(this, "failed to get image", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null){
            mediaPlayer.stop();
            mediaPlayer.release();
        }
        if (videoView != null){
            videoView.suspend();
        }
    }
}
